import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_base_framework/base_library.dart';
import 'package:flutter_base_framework/flutter_base_framework.dart';

class ViewStateWidget<T extends BaseViewModel> extends StatelessWidget {
  // 成功视图
  final Widget successWidget;

  // 自定义错误视图
  final Widget? errorWidget;

  // 错误事件处理
  final VoidCallback? errorRetry;

  // 自定义空数据视图
  final Widget? emptyWidget;

  // 空数据事件处理
  final VoidCallback? emptyRetry;

  // 自定义加载中视图(默认为loading, 可自定义为骨架视图)
  final Widget? loadingWidget;
  final T? init;

  ViewStateWidget(
      {Key? key,
      required this.successWidget,
      this.init,
      this.errorWidget,
      this.errorRetry,
      this.emptyWidget,
      this.emptyRetry,
      this.loadingWidget})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GetBuilder<T>(
        init: init,
        builder: (_) {
          return Container(
            width: double.infinity,
            height: double.infinity,
            child: _buildWidget(_),
          );
        });
  }

  Widget _buildWidget(controller) {
    switch (controller.viewState) {
      case ViewState.busy:
        return _loadingView;
      case ViewState.empty:
        return _emptyView;
      case ViewState.error:
        return _errorView;
      default:
        return successWidget;
    }
  }

  /// 加载中视图
  Widget get _loadingView {
    return Container(
      width: double.infinity,
      height: double.infinity,
      child: loadingWidget ?? BaseLibrary.resConfig.configLoadingView(),
    );
  }

  /// 空数据视图
  Widget get _emptyView {
    return Container(
      width: double.infinity,
      height: double.infinity,
      alignment: Alignment.center,
      child: GestureDetector(
        onTap: emptyRetry,
        child: emptyWidget ?? BaseLibrary.resConfig.configLoadEmptyView(),
      ),
    );
  }

  /// 错误视图
  Widget get _errorView {
    return Container(
      width: double.infinity,
      height: double.infinity,
      alignment: Alignment.center,
      child: GestureDetector(
        onTap: errorRetry,
        child: errorWidget ?? BaseLibrary.resConfig.configLoadErrorView(),
      ),
    );
  }
}
